/*
https://leetcode.cn/problems/longest-univalue-path/
687. 最长同值路径
*/
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int res;
    int longestUnivaluePath(TreeNode* root) {
        res=0;
        dfs(root);
        return res;
    }
    int dfs(TreeNode *root){
        if(root==NULL) return 0;
        int left=dfs(root->left),right=dfs(root->right);
        int a=0,b=0;
        if(root->left&&root->left->val==root->val) a=left+1;
        if(root->right&&root->right->val==root->val) b=right+1;
        res=max(res,a+b);
        return max(a,b);
    }
};